// Json 验证器
class Jv {
    constructor(data, options) {
        this.rules = ['required'];
        this.data = data;
        this.options = options;
        this.errors = {};

        return this.validator();
    }

    get error() {
        const key = Object.keys(this.errors)[0];
        return this.errors[key];
    }

    required(item) {
        const key = item.name;
        const message = typeof item.required == 'string' ? item.required : ('请输入' + item.label);

        const verify = this.each(key.split('.'), (value) => {
            if (value === undefined || value === null || value === '') {
                return false;
            }
        });

        if (verify === false) return message;
    }

    each(keys, verify) {
        let value;
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            if (value) {
                if (Array.isArray(value)) {
                    const ary = value;

                    // 空数组
                    if (ary.length == 0 && verify() == false) return false;

                    for (let i = 0; i < ary.length; i++) {
                        const item = ary[i];
                        value = item[key];
                        if (verify(value) == false) return false;
                    }

                } else {
                    value = value[key];
                }
            } else {
                value = this.data[key];
            }

            if (verify(value) == false) return false;
        }
    }

    validator() {
        const errors = {};

        this.options.map(item => {
            delete item.error;
            for (let i = 0; i < this.rules.length; i++) {
                const rule = this.rules[i];
                if (item[rule]) {
                    const err = this[rule](item);
                    if (err) {
                        errors[item.name] = err;
                        item.error = err;
                        break;
                    }
                }

            }

        });

        this.errors = errors;

        return errors.length ? errors : null;
    }
}

// const jv = new Jv({}, [
//   { label: '姓名', name: 'name', required: true, },
//   { label: '姓名2', name: 'name2', required: true, },
// ]);
// console.log(jv);

export default function(...args) {
    return new Jv(...args);
};
